package com.help.knowhelps.ui;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.help.knowhelps.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnticipateInterpolator;
import android.view.Window;

import com.help.knowhelps.commond.Utils;
import com.help.knowhelps.cropper.CropImageView;
public class EditerImageActivity extends Activity {

	public static final String IMAGE_DATA_URI = "image_data_uri";
	public static final String URI_MAPPING_REALPATH = "uri_mapping_realpath";
	public static final String CROP_IMAGE_PATH = "crop_image_path";
	
	private String mImagePath;
	private int mDegrees;
	private CropImageView CropImageView;
	private int clickNum = 0;
	private final int INCREMENT = 90;
	Matrix matrix = new Matrix(); 
	private float mToDegrees = 0.0f;
	private Bitmap mImageBitmap = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.snap_preview);
		CropImageView = (CropImageView)findViewById(R.id.image_preview);
		Map<String, String> map = null;
		if(getIntent().getExtras() != null){
			Uri uri = (Uri)getIntent().getExtras().get(IMAGE_DATA_URI);
			map = getRealPathFromURI(uri);
		}
		
		if (null != map && map.size() > 0) {
			mImagePath = map.get(Media.DATA);
			try {
				mDegrees = Integer.valueOf(map.get(Media.ORIENTATION));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}else {
			if(getIntent().getExtras() == null || getIntent().getExtras().getString(URI_MAPPING_REALPATH) == null){
//				finish();
			}else {
				mImagePath = getIntent().getExtras().getString(URI_MAPPING_REALPATH);
			}
		}
//		bmp = Utils.getBitmap(getApplicationContext(), mImagePath);
		
		
		CropImageView.setAspectRatio(100, 100);
		CropImageView.setFixedAspectRatio(true);
		mImageBitmap = getImageFromScreen(mImagePath);
		CropImageView.setImageBitmap(mImageBitmap);
		
		
		findViewById(R.id.picture_save).setOnClickListener(listener);
		findViewById(R.id.picture_rotate).setOnClickListener(listener);
		findViewById(R.id.picture_back).setOnClickListener(listener);
	}
	
	OnClickListener listener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.picture_save:{
				
				Bitmap bmp = CropImageView.getCroppedImage();
				final String path = Utils.saveBitmapToDisk(getApplicationContext(), bmp);
				final ProgressDialog dialog = ProgressDialog.show(EditerImageActivity.this, null, getString(R.string.savingImage));
				new Timer().schedule(new TimerTask() {
					
					@Override
					public void run() {
						
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								dialog.dismiss();
								setResult(RESULT_OK, getIntent().putExtra(CROP_IMAGE_PATH, path));
								finish();
							}
						});
						
					}
				}, 3000);
			}
				break;
			case R.id.picture_rotate:{
				clickNum ++;
				
				int flog = clickNum%4;
				if (0 == flog) 
					flog += 4;
				mToDegrees = INCREMENT*flog;
				float fromDegress = INCREMENT*flog - INCREMENT;
				
				CropImageView.rotateImage(90);
				
//				if (mToDegrees == 0.0f || mToDegrees == 360.0f) {
//					;
//				}else{
//					CropImageView.rotateImage((int)mToDegrees);
//				}
//				android.view.animation.RotateAnimation animation = new android.view.animation.RotateAnimation(fromDegress, mToDegrees,  
//	                                                    Animation.RELATIVE_TO_SELF,0.5f,  
//	                                                    Animation.RELATIVE_TO_SELF,0.5f);  
//				animation.setInterpolator(new AnticipateInterpolator());
//				animation.setDuration(600L);  
//				animation.setFillAfter(true);
//				animation.setAnimationListener(new AnimationListener() {
//					
//					public void onAnimationStart(Animation animation) {
//						// TODO Auto-generated method stub
//						
//					}
//					
//					public void onAnimationRepeat(Animation animation) {
//						// TODO Auto-generated method stub
//						
//					}
//					
//					public void onAnimationEnd(Animation animation) {
//						if (mToDegrees == 0.0f || mToDegrees == 360.0f) {
//							;
//						}else{
//							CropImageView.rotateImage((int)mToDegrees);
//						}
//						
//					}
//				});
//				CropImageView.clearAnimation();
//				CropImageView.startAnimation(animation);  
			}
				
				break;
			case R.id.picture_back:{
				setResult(RESULT_CANCELED);
				finish();
			}
	
				break;
			default:
				break;
			}
			
		}
	};
	
	private Bitmap getImageFromScreen(String path){
		Display currentdiDisplay = getWindowManager().getDefaultDisplay();
		float dw = currentdiDisplay.getWidth();
		float dh = currentdiDisplay.getHeight();
		Bitmap returnBitmap = Bitmap.createBitmap((int)dw, (int)dh, Config.ARGB_4444);
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inJustDecodeBounds = true;
		InputStream iti;
		Matrix rotateMatrix = null; 
		try {
			iti = new FileInputStream(path);
			BitmapFactory.decodeStream(iti, null, op);
			if (op.outWidth == -1 && op.outHeight == -1) {
				iti.close();
			}
			iti = new FileInputStream(path);
			BitmapFactory.decodeStream(iti, null, op);
			if (0 != mDegrees) {
				int tmp = 0;
				tmp = op.outHeight;
				op.outHeight = op.outWidth;
				op.outWidth = tmp;
				rotateMatrix = new Matrix();
				rotateMatrix.setRotate(mDegrees); 
			}
			iti.close();
		} catch (Exception e) {
			e.printStackTrace();
			return BitmapFactory.decodeResource(getResources(), R.drawable.baby_avatar);
		}
		
		int wRatio = (int)Math.ceil(op.outWidth/dw);
		int hRatio = (int)Math.ceil(op.outHeight/dh);
		
		if(wRatio > 1 && hRatio > 1){
			if(hRatio > wRatio){
				op.inSampleSize = hRatio;
			}else{
				op.inSampleSize = wRatio;
			}
		}
		
		op.inJustDecodeBounds = false;
		try {
			iti = new FileInputStream(path);
			returnBitmap = BitmapFactory.decodeStream(iti, null, op);
			iti.close();
			if(wRatio == 1 && hRatio == 1)
	            returnBitmap = getMatrixBitmap(returnBitmap, op.outWidth, op.outHeight, dw, dh);
			
			if(returnBitmap.getWidth() < dw && returnBitmap.getHeight()< dh)
				returnBitmap = getMatrixBitmap(returnBitmap, returnBitmap.getWidth(), returnBitmap.getHeight(), dw, dh);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return (0 != mDegrees && null != rotateMatrix) ? Bitmap.createBitmap(returnBitmap, 0, 0, returnBitmap.getWidth(), returnBitmap.getHeight(),  rotateMatrix, true):returnBitmap;
	}
	
	private Bitmap getMatrixBitmap(Bitmap bitmap, float w, float h, float displayW, float displayH) {
		float wRatio = (float)Math.ceil(displayW/w);
		float hRatio = (float)Math.ceil(displayH/h);
		if(hRatio > wRatio)
			matrix.setScale(wRatio, wRatio);
		else 
			matrix.setScale(hRatio, hRatio);
		
		return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
	}
	
	public Map<String, String> getRealPathFromURI(Uri contentUri) {
		if (null == contentUri) 
			return null;
		
        String[] proj = { Media.DATA, Media.ORIENTATION };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        if (null == cursor) 
			return null;
		
        int dataColumn = 0, orientationColumn = 0;
		try {
			dataColumn = cursor.getColumnIndexOrThrow(Media.DATA);
			orientationColumn = cursor.getColumnIndexOrThrow(Media.ORIENTATION);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
        cursor.moveToFirst();
        HashMap<String, String> map = new HashMap<String, String>();
        int orientation = cursor.getInt(orientationColumn);
        String data = cursor.getString(dataColumn);
        if (TextUtils.isEmpty(data)) 
			return null;
		
        map.put(Media.DATA, data);
        map.put(Media.ORIENTATION, String.valueOf(orientation));
        cursor.close();
        return map;
    }
	
	private Bitmap getBitmap(String tag, Uri url, String key)
	{
	 File cacheDir = null;
	 // if the device has an SD card
	 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
	  cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),".OCFL311");
	 } else {
	  // it does not have an SD card
	 }
	 if(!cacheDir.exists())
	      cacheDir.mkdirs();

	 File f=new File(cacheDir, tag);

	 try {
	  Bitmap bitmap=null;
	  InputStream is = null;
	  if (url.toString().contains(key)) {
	   is=getContentResolver().openInputStream(url);
	  } else {
	   is=new URL(url.toString()).openStream();
	  }
	  OutputStream os = new FileOutputStream(f);
	  copyStream(is, os);
	  os.close();
	  return decodeFile(f);
	 } catch (Exception ex) {
	  // something went wrong
	  ex.printStackTrace();
	  return null;
	 }
	}
	private void copyStream(InputStream is, OutputStream os) {
	    int buffer_size = 1024;

	    try {
	      byte[] bytes = new byte[buffer_size];
	      while (true) {
	        int count = is.read(bytes, 0, buffer_size);
	        if (count == -1) {
	          break;
	        }
	        os.write(bytes, 0, count);
	      }

	    } catch (Exception e) {

	    }
	  }
	
	private Bitmap decodeFile(File f) {
	    try {
	      // TODO:Compress image size
	      FileInputStream fileInputStream = new FileInputStream(f);
	      Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
	      return bitmap;

	    } catch (FileNotFoundException e) {
	      return null;
	    }
	  }
}
